package cn.huiyunche.admin.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import cn.huiyunche.base.service.vo.AdminUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * jwt工具.
 * <p>
 *
 * @author zhaoshb
 * @since 0.0.1
 */
public class JwtUtils {

	private static final String NULL_PASS = "****";

	private static final String KEY_ROLES = "roles";

	public static AdminUserVo parseToken(String token, String key) {
		Claims body = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
		String username = body.get("username").toString();
//		List<GrantedAuthority> authorities = JwtUtils.toAuthorities(body);
		return new AdminUserVo(username, NULL_PASS, true);
	}

	public static String generateToken(AdminUserVo user, String key) {
		Claims claims = Jwts.claims();
		claims.put("username", user.getUsername());
		claims.put("password", NULL_PASS);
	
//		claims.put(JwtUtils.KEY_ROLES, JwtUtils.toString(user.getAuthorities()));

		return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact();
	}

	private static List<GrantedAuthority> toAuthorities(Claims body) {
		String strRoles = (String) body.get(JwtUtils.KEY_ROLES);
		String[] roles = strRoles.split(",");
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}

	private static String toString(Collection<GrantedAuthority> authorities) {
		StringBuilder strRoles = new StringBuilder();
		for (GrantedAuthority authority : authorities) {
			strRoles.append(authority.getAuthority() + ",");
		}
		return strRoles.substring(0, strRoles.length() - 1);
	}

}
